var $mainbody = $("#mainbody");

var $userDateStart = $('#userDateStart');//开始日期
var $userDateEnd = $('#userDateEnd');//结束日期

var $userStatus = $('#userStatus');//选择查看的当前用户的状态
var $userSearch = $('#userSearch');//输入进行模糊搜索的电话号码

//分页信息
var staffInfo = {};
staffInfo.data = {
	pageSize:10,//每页记录数
	totalSize:0,//总记录数
	curPage:1,//当前页 1..n
	totalPage:0//总页数
};

//分页操作
staffInfo.page = {
	/**
	 * @description 转到第一页
	 * @author 
	 */
	turnFirst : function() {
		if(staffInfo.data.curPage == 1){
			promptMessge('已经是第一页',1000);
		}else{
			staffInfo.data.curPage = 1;
			//QueryResult();
		}
	},
	/**
	 * @description 转到尾页
	 * @author 
	 */
	turnEnd : function() {
		if(staffInfo.data.curPage == staffInfo.data.totalPage){
			promptMessge('已经是最后一页',1000);
		} else {
			staffInfo.data.curPage = staffInfo.data.totalPage;
			//QueryResult();
		}
	},
	/**
	 * @description 转到上页
	 * @author 
	 */
	turnPre : function() {
		if (staffInfo.data.curPage != 1) {
			staffInfo.data.curPage -= 1;
			//QueryResult();
		} else {
			promptMessge('已经是第一页',1000);
		}
	},
	/**
	 * @description 转到下页
	 * @author 
	 */
	turnNext : function() {
		if (staffInfo.data.curPage+1 <= staffInfo.data.totalPage) {
			staffInfo.data.curPage += 1;
			//QueryResult();
		} else {
			promptMessge('已经是最后一页',1000);
		}
	},
	//container 容器，count 总页数 pageindex 当前页数
	setPage : function (container, count, pageindex) {
		var container = container;
		var count = count;
		var pageindex = pageindex;
		var a = [];
		//总页数少于10 全部显示,大于10 显示前3 后3 中间3 其余....
		if (pageindex == 1) {
			a[a.length] = '<li class="disabled"><a>&lt;</a></li>';
		} else {
			a[a.length] = '<li><a>&lt;</a></li>';
		}
		function setPageList() {
			if (pageindex == i) {
				a[a.length] = '<li class="active"><a>' + i + '</a></li>';
			} else {
				a[a.length] = "<li><a>" + i + "</a></li>";
			}
		}

		//总页数小于10
		if (count <= 10) {
			for (var i = 1; i <= count; i++) {
				setPageList();
			}
		} else {
			//总页数大于10页
			if (pageindex <= 4) {
				for (var i = 1; i <= 5; i++) {
					setPageList();
				}
				a[a.length] = '<li class="disabled"><a>...</a></li><li><a>' + count + '</a></li>';
			} else if (pageindex >= count - 3) {
				a[a.length] = '<li><a>1</a></li><li class="disabled"><a>...</a></li>';
				for (var i = count - 4; i <= count; i++) {
					setPageList();
				}
			}
			else { //当前页在中间部分
				a[a.length] = '<li><a>1</a></li><li class="disabled"><a>...</a></li>';
				for (var i = pageindex - 2; i <= pageindex + 2; i++) {
					setPageList();
				}
				a[a.length] = '<li><a>...</a></li><li><a>' + count + '</a></li>';
			}
		}
		if (pageindex == count) {
			a[a.length] = '<li class="disabled"><a>&gt; </a></li>';
		} else {
			a[a.length] = "<li><a>&gt; </a></li>";
		}
		container.innerHTML = a.join("");

		//事件点击
		(function () {
			var oAlink = container.getElementsByTagName("a");
			var inx = pageindex; //初始的页码
			oAlink[0].onclick = function () { //点击上一页
				if (inx == 1) {
					return false;
				}
				inx--;
				staffInfo.page.setPage(container, count, inx);
				staffInfo.data.curPage = inx;
				//展示销售品列表
				staffInfo.queryList();
				return false;
			}
			for (var i = 1; i < oAlink.length - 1; i++) { //点击页码
				if(i === staffInfo.data.curPage){
					continue;
				}
				oAlink[i].onclick = function () {
					inx = parseInt(this.innerHTML);
					staffInfo.page.setPage(container, count, inx);
					staffInfo.data.curPage = inx;
					//展示销售品列表
//			    staffInfo.layOut.renderOfferList(staffInfo.data.categoryNodeId);
					staffInfo.queryList();
					return false;
				}
			}
			oAlink[oAlink.length - 1].onclick = function () { //点击下一页
				if (inx == count) {
					return false;
				}
				inx++;
				staffInfo.page.setPage(container, count, inx);
				staffInfo.data.curPage = inx;
				//展示销售品列表
//			  staffInfo.layOut.renderOfferList(staffInfo.data.categoryNodeId);
				staffInfo.queryList();
				return false;
			}
		})();
	}
};

/**
 * 设置页码
 */
staffInfo.renderPageInfo = function () {
	$(".pagination_c").empty();
	$(".pagination_c").append(
		'<ul class="pagination">'
//	        + '<li><a href="#">&lt;</a></li>'
//	        + '<li><a href="#" class="current">1</a></li>'
//	        + '<li><a href="#">2</a></li>'
//	        + '<li><a href="#">3</a></li>'
//	        + '<li><a href="#">...</a></li>'
//	        + '<li><a href="#">198</a></li>'
//	        + '<li><a href="#">200</a></li>'
//	        + '<li><a href="#">&gt; </a></li>'
		+ '</ul>'
	);
	staffInfo.page.setPage($(".pagination_c").find(".pagination")[0], staffInfo.data.totalPage, staffInfo.data.curPage);
};

//staffInfo.queryListCount= function(){
//	var param ={  "pageNo":1, "pageSize":10 }
//	Ajax.ajax({
//		url:"/shopService/ad/queryAds",
//		data:JSON.stringify(param),
//		headers: {'Content-type': 'application/json;charset=UTF-8'},
//		type:"POST",
//		success:function(res){
//			if (res.resultCode == 0) {
//				staffInfo.data.totalSize = res.data.totalRow;
//				staffInfo.data.totalPage = res.data.totalPage;
//				staffInfo.renderPageInfo();
//			}
//		}
//
//	});
//}

/**
 * 获取用户数据
 */
staffInfo.queryList= function(){
	var param = {
		start: $userDateStart.val().trim(),
		end: $userDateEnd.val().trim(),
		phone: $userSearch.val().trim(),
		status: $userStatus.val(),
		cPage: staffInfo.data.curPage,
		pSize: staffInfo.data.pageSize
	};
	Ajax.ajax({
		url: "/user/qryUserList",
		data: param,
		type: "GET",
		dataType: 'json',
		success:function(res){
			if (res.resultCode == 0) {
				staffInfo.data.totalSize = res.data.totalRow;
				staffInfo.data.totalPage = res.data.totalPage;
				staffInfo.renderPageInfo();
				$(".page-pageno").html(staffInfo.data.curPage);
				$(".page-totalcount").html(staffInfo.data.totalSize);
				$(".page-pageno").html(staffInfo.data.curPage);
				$(".page-pagecount").html(staffInfo.data.totalPage);
				staffInfo.showTabel(res.data.list);
			}
		}
		
	});
}

/**
 * 展示用户数据
 * @param list
 */
staffInfo.showTabel= function(list){
	$mainbody.empty();
	$.each(list,function(n,v) {
		/*		<tr>
		 <td><input type="checkbox" class=""></td>
		 <td>109332321@qq.com</td>
		 <td>Mark</td>
		 <td><img src="/shop/assets/img/avatar2.gif" alt="Mark"/></td>
		 <td>周董</td>
		 <td>18509090909</td>
		 <td>正常</td>
		 <td>2017-02-28 23:22</td>
		 <td><button class="btn btn-primary btn-trans btn-xs">禁用</button></td>
		 </tr>*/
		//开始组装
		var $tr = $("<tr>");
		var $checkbox = $('<td><input type="checkbox" data-id="' + v.id + '"></td>');
		var $id = $('<td>' + v.id + '</td>');
		var $phone = $("<td>" + v.phone + "</td>");
		var $orderCnt = $("<td>" + v.total_order_cnt + "</td>");
		var $totalOrderPrice = $("<td>" + v.total_order_price + "</td>");
		var $lastLoginTime = $("<td>" + v.last_login_time + "</td>");
		var $lastBuyTime = $("<td>" + (v.last_buy_time == null ? '' : v.last_buy_time) + "</td>");
		var userStatus = parseInt(v.status) === 1 ? true : false;
		var $status = $("<td>" + (userStatus ? '正常' : '禁用') + "</td>");

		var $buttonOp = $('<button class="btn btn-primary btn-trans btn-xs btn-user-op" data-id="' + v.id + '" data-status="' + v.u_status + '">' + (userStatus ? '禁用' : '启用') + '</button>');
		var $buttonResetPwd = $('<button class="btn btn-primary btn-trans btn-xs btn-user-resetPwd" data-id="' + v.id + '" data-status="' + v.u_status + '">' + '重置密码' + '</button>');
		var $buttonDetail = $('<button class="btn btn-primary btn-trans btn-xs btn-user-detail" data-id="' + v.id + '" data-status="' + v.u_status + '">' + '详情' + '</button>');
		var $btnTd = $('<td>').append($buttonOp).append($buttonResetPwd).append($buttonDetail);
		$tr.append($checkbox, $id, $phone,$orderCnt,$totalOrderPrice,$lastLoginTime,$lastBuyTime, $status, $btnTd);
		$mainbody.append($tr);
	});
	//详情 按钮事件设置
	$('button.btn-user-detail',$mainbody).on('click',function () {

		var id =  $(this).attr('data-id');
		$('#mainframe').load("/user/userDetail?userId="+id);

	});
	//禁用\启用 按钮事件设置
	$('button.btn-user-op',$mainbody).on('click',function () {
		var userStatus = $(this).attr('data-status');
		var param = {
			id: $(this).attr('data-id'),
			u_status: userStatus == 0 ? 1 : 0
		}
		Ajax.ajax({
			url: "/user/updateStatus",
			data: param,
			type: "POST",
			dataType: 'json',
			success: function (res) {
				if (res.resultCode == 0) {
					staffInfo.queryList();
				} else {
					alert("操作失败");
				}
			},
			error: function(){
				alert("操作失败");
			}
		});
	});

	//重置密码 按钮事件设置
	$('button.btn-user-resetPwd',$mainbody).on('click',function () {
		var param = {
			userId: $(this).attr('data-id'),
		}
		Ajax.ajax({
			url: "/user/resetPwd",
			data: param,
			type: "POST",
			dataType: 'json',
			success: function (res) {
				if (res.resultCode == 0) {
					alert("密码重置为123456");
				} else {
					alert("操作失败");
				}
			},
			error: function(){
				alert("操作失败");
			}
		});
	});

	//选中当前行事件设置
	$('tr', $mainbody).on('click',function (e) {
		var $checkbox = $(this).find(':checkbox');
		if(e.target != $checkbox[0]){
			$checkbox.click();
		}
	});
}



$(function(){
	staffInfo.queryList();

	//选择查看的用户状态
	$userStatus.on('change',function(){
		staffInfo.queryList();
	});

	//开始\结束 日期选择
	$userDateStart.datepicker({
		dateFormat: 'yy-mm-dd'
	});
	$userDateEnd.datepicker({
		dateFormat: 'yy-mm-dd'
	});

	//查找按钮
	$('#userSearchBtn').on('click',function(){
		staffInfo.data.curPage = 1;
		staffInfo.queryList();
	});

	//每页显示的数据数切换
	$(".page-pagesize").change(function(){
		staffInfo.data.pageSize = $(this).val();
		staffInfo.data.curPage=1;
		staffInfo.queryList();
	});

	//表格头部选中全部
	$('#checkAll').on('click',function(){
		if(this.checked){
			//选中全部
			$mainbody.find(':checkbox').prop('checked', true);
		} else {
			$mainbody.find(':checkbox').prop('checked', false);
		}
	});

	//批量禁用
	$('#btnOffAll').on('click',function(){
		var $userList = $mainbody.find(':checked');
		var l = $userList.length;
		if(l <= 0){
			alert('请先选择要禁用的用户');
		} else if(confirm('确认禁用选中用户？')) {
			var idList = Array.prototype.map.call($userList,function(obj){
				return obj.getAttribute('data-id');
			});
			var param = {
				ids: idList.join(','),
				u_status: 0
			}
			Ajax.ajax({
				url: "/user/updateBatch",
				data: param,
				type: "POST",
				dataType: 'json',
				success:function(res){
					if (res.resultCode == 0) {
						staffInfo.queryList();
					}else{
						alert('操作失败');
					}
				},
				error: function(){
					alert('操作失败');
				}
			});
		}
	})
});